package org.example;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.*;


public class UserDataListener extends AnalysisEventListener<UserData> {

    private Validator validator = Validation.buildDefaultValidatorFactory().getValidator();


    private List<UserData> list = new ArrayList<>();

    private Map<Integer, String> headMap;


    private Map<Integer, String> errorMap = new TreeMap<>();


    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        this.headMap = headMap;
    }

    @Override
    public void invoke(UserData data, AnalysisContext context) {
        data.setRowIndex(context.readRowHolder().getRowIndex());
        Set<ConstraintViolation<UserData>> violations = validator.validate(data);
        if (violations.isEmpty()) {
            list.add(data);
        } else {
            for (ConstraintViolation<UserData> violation : violations) {
                errorMap.put(data.getRowIndex(), "第" + data.getRowIndex() + "行，" + violation.getMessage());
            }
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
    }


    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
            errorMap.put(excelDataConvertException.getRowIndex(),
                    "第" + excelDataConvertException.getRowIndex() + "行，"
                            + headMap.get(excelDataConvertException.getColumnIndex())
                            + "格式不正确，原始数据：" + excelDataConvertException.getCellData());
        }
    }


    public List<UserData> getList() {
        return list;
    }

    public Map<Integer, String> getErrorMap() {
        return errorMap;
    }
}